#!/bin/bash

This script requires env var $GITHUB_PUSH_TOKEN to be set
if [ -z ${GITHUB_PUSH_TOKEN} ];
then
	echo "Need \$GITHUB_PUSH_TOKEN";
	exit 1
fi

echo "Cloning a clean state..."
git clone https://github.com/${TRAVIS_REPO_SLUG}.git clone

cd clone

echo "Cleaning previous databases from git objects..."

./scripts/clean-git-objects
stat=$?
if [ $stat -ne 0 ]
then
	echo "Exited with ${stat}"
	exit 1
fi

./scripts/update-databases

stat=$?

# Process previous script exit code
if [ $stat -eq 65 ];
then
	echo "Nothing to push"
	exit 0
elif [ $stat -ne 0 ]
then
	echo "Exited with ${stat}"
	exit 1
fi

git add redist
git commit -m "Update redistribution (cron job ${TRAVIS_JOB_NUMBER})" -m "${TRAVIS_JOB_WEB_URL}" --author="Travis CI <builds@travis-ci.org>"
git push --force https://${GITHUB_PUSH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git master

echo "Updates pushed to GitHub remote"
exit 0
